<template>
	<view>
		<view class="form-box">
			<u--form :model="orderForm" ref="uForm" :errorType="['toast']" labelWidth="100">
				<u-form-item label="开单时间" prop="creationTime" borderBottom @click="showCreTimePicker = true">
					<view class="text-align-right">
						<text class="line-gray">{{orderForm.creationTime}}</text>
					</view>
					<u-icon slot="right" name="arrow-right"/>
				</u-form-item>
				<u-form-item label="请选择客户" prop="userName" @click="!isEdit?$u.route('/pages/selectPage/client', {isRadio: true}):''">
					<u-input v-model="orderForm.userName" placeholder="请选择" border="none" inputAlign="right" disabled disabledColor="#fff"></u-input>
					<u-icon slot="right" name="arrow-right"/>
				</u-form-item>
				<view class="gap">消费项目</view>
				<view class="">
					<view class="bg-white padding-20 mb-20" v-for="(item, index) in orderForm.items" :key="index">
						<view>
							<view class="flex justify-between align-center">
								<view>
									<view>{{item.itemName}}</view>
									<view class="mt-6 fsize-28 line-gray" v-if="item.itemType === 21">划卡项目 剩余{{item.balance }}次</view>
									<view class="mt-6 fsize-28 line-gray" v-if="item.itemType === 18">优惠券</view>
								</view>
								<u-number-box v-model="item.nums" :max="item.balance || 999" @overlimit="ev=>setNums(ev, item.itemId)">
									<view slot="minus" class="number-btn">
										<u-icon name="minus" size="12"></u-icon>
									</view>
									<text slot="input" class="input">{{item.nums}}</text>
									<view slot="plus" class="number-btn">
										<u-icon name="plus" size="12"></u-icon>
									</view>
								</u-number-box>
							</view>
							<view class="width-680 bg-white-ling border-radius-10 padding-20 ml-30 mt-20" v-if="item.itemType === 21"> 
								<view class="flex justify-between align-center height-60">
									<text>服务人员</text>
									<view class="flex justify-end align-center" @click="$u.route('/pages/selectPage/staff',{index: index, type: '1'})">
										<text v-if="$u.test.isEmpty(item.staffId)" class="fsize-28 text-pla">请选择</text>
										<text v-else class="fsize-28">{{item.staffName}}</text>
										<u-icon name="arrow-right" color="#606266"/>
									</view>
								</view>
							</view>
							<view v-if="item.itemType === 1 || item.itemType === 11 || item.itemType === 12">
								<view class="text-align-right pt-20 pb-20">￥{{item.price}}</view>
								<view class="width-680 bg-white-ling border-radius-10 padding-20 ml-30">
									<view class="flex justify-between align-center height-60" v-if="item.itemType === 11">
										<text class="fsize-28">服务员</text>
										<view class="flex justify-end align-center" @click="$u.route('/pages/selectPage/staff',{index: index, type: '1'})">
											<text v-if="$u.test.isEmpty(item.staffId)" class="fsize-28 text-pla">请选择</text>
											<text v-else class="fsize-28">{{item.staffName}}</text>
											<u-icon name="arrow-right" color="#606266"/>
										</view>
									</view>
									<view class="flex justify-between align-center height-60">
										<text class="fsize-28">销售员</text>
										<view class="flex justify-end align-center" @click="$u.route('/pages/selectPage/staff',{index: index, type: '2'})">
											<text v-if="$u.test.isEmpty(item.salerId)" class="fsize-28 text-pla">请选择</text>
											<text v-else class="fsize-28">{{item.salerName}}</text>
											<u-icon name="arrow-right" color="#606266"/>
										</view>
									</view>
									<view class="flex justify-between align-center height-60" style="border-bottom: 1px #e54d42 solid;">
										<text class="fsize-28">折后价<text class="ml-6 fsize-24 line-red">( 可手动设置 )</text></text>
										<u-input v-model="item.realPrice" inputAlign="right" border="none" type="digit" />
									</view>
								</view>
								<view class="flex justify-end align-center mt-20">
									<text class="ml-10">小计</text>
									<text class="line-red ml-10">￥{{(item.realPrice * item.nums).toFixed(2)}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="padding-20 bg-white" @click="addGoods">
					<view class="add-goods-btn">+ 添加商品</view>
				</view>
				<view class="gap">订单信息</view>
				<u-form-item label="优惠券" prop="reduceName" v-if="orderForm.userId" @click="$u.route('/pages/selectPage/coupon', {userId: orderForm.userId})">
					<u-input border="none" v-model="orderForm.reduceName" disabled disabledColor="#fff" inputAlign="right" />
					<u-icon slot="right" name="arrow-right"/>
				</u-form-item>
				<u-form-item label="备注" prop="remark">
					<u-input border="none" v-model="orderForm.remark" placeholder="请输入" inputAlign="right" />
				</u-form-item>
			</u--form>
			<view class="height-260"/>
			<view class="bottom-button">
				<view class="flex justify-end align-center pt-20 pb-20">
					<text class="fsize-26">待收款</text>
					<text class="fsize-36 line-red ml-10">￥{{ totalPrice }}</text>
				</view>
				<view class="flex justify-between align-center">
					<view class="width-330">
						<u-button text="取消" @click="onCancel"></u-button>
					</view>
					<view class="width-330">
						<u-button type="primary" color="#e54d42" text="开单收款" @click="submit"></u-button>
					</view>
				</view>
			</view>
		</view>
		<u-datetime-picker
			:show="showCreTimePicker"
			:value="orderForm.creationTime"
			@confirm="confirmDateTime"
			@cancel="showCreTimePicker = false"
			model="datetime"
		></u-datetime-picker>
	</view>
</template>

<script>
	import getDateTime from '@/common/getDataTime.js'
	import { mapState } from 'vuex'
	export default {
		data(){
			return {
				isEdit: false,
				showCreTimePicker: false,
				orderForm: {
					creationTime: '',
					userName: '',
					userId: '',
					remark:'',
					realAmout: 0,
					items:[],
					reduceAmount: 0,
					reduceName: "",
					couponCode: ""
				},
				rules: {
					userName: [{
						required: true,
						message: '请先选择客户!',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		onLoad(opt) {
			if(opt.id){
				this.isEdit = true
				this.getDetail(opt.id)
			}
			this.orderForm.storeId = this.store.id
			this.orderForm.creationTime = getDateTime.dateTimeStr('y/m/d h:i:s')
			// 监听事件
			uni.$on('client', obj => {
				this.orderForm.userName = obj.nickName
				this.orderForm.userId = obj.id
				this.orderForm.reduceAmount = 0
				this.orderForm.reduceName = ""
				this.orderForm.couponCode = ""
			})
			uni.$on('select-staff', obj => {
				this.orderForm.items[obj.index].staffId = obj.id
				this.orderForm.items[obj.index].staffName = obj.nickName
				this.$forceUpdate()
			})
			uni.$on('select-saler', obj => {
				this.orderForm.items[obj.index].salerId = obj.id
				this.orderForm.items[obj.index].salerName = obj.nickName
				this.$forceUpdate()
			})
			uni.$on('coupon', obj => {
				this.orderForm.reduceAmount = obj.reduceAmount
				this.orderForm.couponCode = obj.couponCode
				this.orderForm.reduceName = obj.expression2
			})
			uni.$on('gift', list => {
				const itemMap = {};
				const array1 = this.orderForm.items;
				const array2 = list;
				// 构建哈希表
				array1.forEach(item => {
				  itemMap[item.itemId] = item;
				});
				array2.forEach(item => {
				  const existingItem = itemMap[item.itemId];
				  if (existingItem) {
				    existingItem.nums += item.nums;
				  } else {
				    array1.unshift(item);
				  }
				});
				this.orderForm.items = array1;
				// console.log('this.orderForm.items', this.orderForm.items)
				// this.orderForm.realAmout = this.getSum(this.orderForm.items)
			})
		},
		computed: {  
			...mapState(['store']),
			totalPrice() {  
				let total = 0;  
				for (let item of this.orderForm.items) {  
					if (item.itemType !== 21 && item.itemType !== 18) {  
						total += item.realPrice * item.nums;  
					}  
				}
				total = (total - this.orderForm.reduceAmount).toFixed(2);
				if(total < 0){
					total = 0
				}
				this.orderForm.realAmout = total
				return total
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onUnload() {
			// 移除监听事件
			uni.$off('client')
			uni.$off('gift')
			uni.$off('select-staff')
			uni.$off('select-saler')
			uni.$off('coupon')
		},
		methods: {
			onCancel(){
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			setNums(type, itemId){
				if(type === 'minus'){
					// this.orderForm.items.splice(ix, 1)
					this.orderForm.items = this.orderForm.items.filter(im=> im.itemId !== itemId)
				}
			},
			addGoods(){
				this.$refs.uForm.validate().then(res=>{
					uni.$u.route('/pages/selectPage/giftItems', {userId: this.orderForm.userId})
				})
			},
			getSum(items){
				const num = items.reduce((acc, cur) => {
					if(cur.itemType === 21){
						return 0
					}else {
						return acc + cur.price * cur.nums
					}
				}, 0)
				return num
			},
			confirmDateTime(e){
				this.orderForm.creationTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				this.showCreTimePicker = false
			},
			getDetail(id){
				this.$reqJsonPost('GetStaffAppointmentDetail', { id: id }).then(res=>{
					this.orderForm = {...this.orderForm, ...res.data}
				})
			},
			submit() {
				// console.log("this.orderForm", this.orderForm)
				this.$refs.uForm.validate().then(res => {
					this.$reqJsonPost('CreateProjectOrder', this.orderForm).then(res=>{
						if(res.otherData.payStatus===2){
								uni.redirectTo({
									url: '/pages/order/index'
								});
						}else {
							uni.redirectTo({
								url: `/pages/payment/qrc?id=${res.data}&&pages=/pages/order/index&&orderType=${100}`
							})
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.gap {
		padding: 20rpx;
		color: #aaa;
		font-size: 28rpx;
	}
	.number-btn {
		width: 52rpx;
		height: 52rpx;
		border: 2rpx #bbb solid;
		@include flex;
		justify-content: center;
		align-items: center;
	}
	.input {
		width: 100rpx;
		height: 52rpx;
		line-height: 52rpx;
		border-top: 2rpx #bbb solid;
		border-bottom: 2rpx #bbb solid;
		padding: 0 10rpx;
		text-align: center;
	}
	.add-goods-btn{
		border: 1px #e54d42 solid;
		text-align: center;
		padding: 20rpx;
		color:#e54d42;
		font-weight: 600;
		border-radius: 6rpx;
		background-color: rgba(229,77,66, 0.1);
	}
</style>